package com.neurotech.pcc.widgets

import android.content.Context
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.text.*
import android.util.AttributeSet
import android.view.Gravity
import android.view.KeyEvent
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.neurotech.pcc.R
import java.util.regex.Pattern


/**
 * IPv4地址输入框
 * Created by shenhua on 2018/10/11.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
class IpInputLayout @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defAttrStyle: Int = 0)
    : LinearLayout(context, attributeSet, defAttrStyle) {

    private var current = 0
    private var edits: List<IpEditText> = ArrayList()

    init {
        orientation = HORIZONTAL
        val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams.weight = 1f
        val inputListener = object : InputListener {
            override fun onPrevious() {
                if (current > 0) {
                    edits[current - 1].requestFocus()
                }
            }

            override fun onNext() {
                if (current < edits.size - 1) {
                    edits[current + 1].requestFocus()
                }
            }
        }

        val ipEditText1 = IpEditText(context, inputListener)
        val ipEditText2 = IpEditText(context, inputListener)
        val ipEditText3 = IpEditText(context, inputListener)
        val ipEditText4 = IpEditText(context, inputListener)

        addView(ipEditText1, layoutParams)
        addView(DotTextView(context))
        addView(ipEditText2, layoutParams)
        addView(DotTextView(context))
        addView(ipEditText3, layoutParams)
        addView(DotTextView(context))
        addView(ipEditText4, layoutParams)

        edits = object : ArrayList<IpEditText>() {
            init {
                add(ipEditText1)
                add(ipEditText2)
                add(ipEditText3)
                add(ipEditText4)
            }
        }

        for (i in edits.indices) {
            edits[i].setOnFocusChangeListener { _, _ ->
                current = i
            }
        }
    }

    fun fitIp(ip: String?) {
        if (TextUtils.isEmpty(ip)) {
            return
        }
        val ips = ip?.split(".")
        for (i in edits.indices) {
            edits[i].setText(ips?.get(i))
            edits[i].setSelection(ips?.get(i)?.length!!)
        }
    }

    fun ip(): String {
        var result = ""
        for (i in edits.indices) {
            result += edits[i].text.toString() + "."
        }
        return result.substring(0, result.length - 1)
    }

    companion object {
        fun isIp(addr: String): Boolean {
            if (addr.length < 7 || addr.length > 15 || "" == addr) {
                return false
            }
            val rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}"
            val pat = Pattern.compile(rexp)
            val mat = pat.matcher(addr)
            return mat.find()
        }
    }

    inner class IpEditText constructor(context: Context, inputListener: InputListener?) : EditText(context) {

        init {
            maxLines = 1
            filters = arrayOf<InputFilter>(InputFilter.LengthFilter(3))
            inputType = InputType.TYPE_CLASS_NUMBER
            gravity = Gravity.CENTER
            isFocusable = true
//            background = ColorDrawable(Color.TRANSPARENT)
            addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s != null && s.isNotEmpty()) {
                        val value = s.toString().toInt()
                        if (value > 255) {
                            error()
                        } else {
                            if (s.length == 3) {
                                inputListener?.onNext()
                            }
                        }
                    }
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    normal()
                }
            })

            setOnKeyListener { _, keyCode, event ->
                if (keyCode == KeyEvent.KEYCODE_DEL && event.action == KeyEvent.ACTION_DOWN) {
                    if (text.isEmpty()) {
                        inputListener?.onPrevious()
                    }
                }
                return@setOnKeyListener false
            }
        }

        fun error() {
            setTextColor(Color.RED)
        }

        fun normal() {
            setTextColor(ContextCompat.getColor(context, R.color.colorPrimary))
        }
    }

    inner class DotTextView constructor(context: Context) : TextView(context) {
        init {
            text = "."
            gravity = Gravity.BOTTOM
        }
    }

    interface InputListener {
        fun onPrevious()
        fun onNext()
    }
}